//
//  ComposeViewController.swift
//  Sina
//
//  Created by maling  on 15/11/15.
//  Copyright © 2015年 maling . All rights reserved.
//

import UIKit
import SVProgressHUD

// MARK: - 撰写控制器
class ComposeViewController: UIViewController {

    /// 表情键盘视图
    private lazy var emoticonView: EmoticonView = EmoticonView { [weak self] (emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
    }
    

    
    
    // MARK: -点击监听方法
    @objc private func close() {
    
        // 辞去第一响应者
        textView.resignFirstResponder()
        // dismiss方法
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK: 发布微博
    @objc private func send() {
        
        // 1. 获取微博内容
        let text = textView.emoticonText
        
        // 2.发布微博
        let image = UIImage(named: "123")
        NetworkTools.sharedTools.sendStatus(text, image: image) { (result, error) -> () in
            
            if error != nil {
            
                print("出错了")
                SVProgressHUD.showErrorWithStatus("网络不给力啊")
                
                return
            }
            
            // 关闭控制器
            self.close()
        }
        
        

   }
    @objc private func selectEmoticon() {
    
        // 如果使用的时系统的键盘 打印的时nil
      print("选择表情\(textView.inputView)")
        
        // 1》 推掉系统的键盘
        textView.resignFirstResponder()
        
        // 2》 重新设置表情键盘
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        
        // 3》 激活键盘
        textView.becomeFirstResponder()
    }
    /**
    userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        UIKeyboardIsLocalUserInfoKey = 1;
    }
    */
    // MARK: 监听键盘的改变
    @objc private func keyboardChanged(notification: NSNotification) {
        print(notification)
        
        // 1》 获取目标的 rect - 字典中的结构体是 NSValue 类型的
        let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        // 获取目标的动画时长
        let duration = (notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    
        // 获取动画曲线值
        let curve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        // 键盘的偏移
        let offSet =  -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        
        // 2> 跟新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offSet)
        }
        
        // 3》动画
        UIView.animateWithDuration(duration) { () -> Void in
           
            // 设置动画曲线
            /**
               曲线值 = 7
               - 如果之前的动画没有完成，有启动了其他动画 让动画的图层直接运动到后续动画的目标位置
               - 一旦设置了 ‘7’ 动画时长无效 动画时长变成 0.5s
            */
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            // 强制跟新位置
            self.view.layoutIfNeeded()
        }
        
        // 设置动画时长 - keyPath 将动画添加到图层
        let animal = toolBar.layer.animationForKey("position")
        print("动画时长\(animal?.duration)")
    
    }
    
    // MARK: - 视图生命周期
    override func loadView() {
        view = UIView()
        
        setipUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // MARK: 监听键盘的点击
        // 添加键盘通知
        let notification = NSNotificationCenter.defaultCenter()
    
        // 添加监听
        notification.addObserver(self,
            selector: "keyboardChanged:",
            name: UIKeyboardWillChangeFrameNotification,
            object: nil)
    }
    
    // 注销通知
    deinit {
    
        // MARK: 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    
    // MARK: - 激活键盘- 
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    
    // MARK: - 懒加载toolbar
    private lazy var toolBar = UIToolbar()
    
    // MARK: -文本视图
    private lazy var textView: UITextView = {
        
        // 创建一个textView
        let tv = UITextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.magentaColor()
       
        // 始终允许垂直滚动
        tv.alwaysBounceVertical = true
        // 拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        // MARK: 设置代理
        tv.delegate = self
        
        return tv
        }()
    // MARK: - 设置占位标签
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事...",
        fontSize: 18, color: UIColor.lightGrayColor())
  
}

// MARK: - 代理方法
extension ComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
        
    }
}

private extension ComposeViewController {

     func setipUI() {
    
       // 设置背景
        view.backgroundColor = UIColor.whiteColor()
        
        // 准备导航条按钮
        prepareNavigationBar()
        // 准备toolBar
        prepareToolBar()
        // 准备文本视图
        prepareTextView()
        
        // 输入辅助视图 当推掉键盘之后 toolbar 会消失
        
    }
    ///   设置导航栏
    private func prepareNavigationBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
    
        // 禁用按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 设置配图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        navigationItem.titleView = titleView
        
        // 设置标题视图
        let titleLabel = UILabel(title: "发微博", fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.userAccount?.screen_name ?? "",
            fontSize: 13, color: UIColor.lightGrayColor())
        
        
        
        // 添加到导航条上面
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        // 自动布局
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
    }
    
    ///  设置toolBar
    private func prepareToolBar() {
       
        
        // 1》 添加控件
        view.addSubview(toolBar)
        
        // 设置背景色
        toolBar.backgroundColor = UIColor(red: 234/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1)
        
        // 2> 自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        
        // 3> 添加按钮
        let itemSettings = [["imageName" : "compose_toolbar_picture"],
            ["imageName" : "compose_mentionbutton_background"],
            ["imageName" : "compose_trendbutton_background"],
            ["imageName" : "compose_emoticonbutton_background", "actionName" : "selectEmoticon"],
            ["imageName" : "compose_addbutton_background"]]
        
        // 创建一个 items 数组
        var items = [UIBarButtonItem]()
        
        // 遍历字典数组
        for dict in itemSettings {
/*
            let button = UIButton(imageName: dict["imageName"]!, backImage: nil)
            
            // 判断 actionName 
            if let actionName = dict["actionName"] {
                // 监听按钮的点击
                button.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            let item = UIBarButtonItem(customView: button)
            
            // 添加到 items 数组中
            items.append(item)
*/
            // 重构后的代码
            items.append(UIBarButtonItem(imageName: dict["imageName"]!,
                target: self, actionName: dict["actionName"]))
            
            // 添加弹簧 撑开按钮
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
            
            
        }
        
        // 移除最后一个弹簧
        items.removeLast()
        
        // 一旦复制，相当于做了一次拷贝
        toolBar.items = items

    }
    
    private func prepareTextView() {
    
        // 添加控件
        view.addSubview(textView)
        
        // 设置自动布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        // 占位标签文本
//        textView.text = "分享新鲜事..."
        // 添加标签
        textView.addSubview(placeHolderLabel)

        // 设置占位标签自动布局
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    
    
}